import { createRouter, createWebHistory } from 'vue-router';
import { useAuthStore } from '@/stores/auth';

// 基础路由 - 无需权限
const baseRoutes = [
    {
        path: '/login',
        name: 'Login',
        component: () => import('@/views/LoginView.vue'),
        meta: { requiresAuth: false, title: '登录' }
    },
    {
        path: '/register',
        name: 'Register',
        component: () => import('@/views/RegisterView.vue'),
        meta: { requiresAuth: false, title: '注册' }
    },
    {
        path: '/forbidden',
        name: 'Forbidden',
        component: () => import('@/views/Exception/Forbidden.vue'),
        meta: { requiresAuth: false, title: '无权限访问' }
    },
    {
        path: '/error',
        name: 'Error',
        component: () => import('@/views/Exception/ErrorPage.vue'),
        meta: { requiresAuth: false, title: '错误页面' }
    }
];

// 认证后路由 - 需要登录
const authRoutes = [
    {
        path: '/dashboard',
        name: 'Dashboard',
        component: () => import('@/views/DashboardView.vue'),
        meta: { requiresAuth: true, title: '仪表盘' }
    },
    {
        path: '/user/profile',
        name: 'UserProfile',
        component: () => import('@/views/UserProfile.vue'),
        meta: { requiresAuth: true, title: '个人资料' }
    }
];

// 角色特定路由 - 按角色分组
const roleRoutes = {
    ADMIN: [
        {
            path: '/admin/dashboard',
            name: 'AdminDashboard',
            component: () => import('@/views/admin/AdminDashboard.vue'),
            meta: { requiresAuth: true, roles: ['ADMIN'], title: '管理员面板' }
        }
    ],
    TEACHER: [
        {
            path: '/teacher/dashboard',
            name: 'TeacherDashboard',
            component: () => import('@/views/TeacherManagement.vue'),
            meta: {requiresAuth: true, roles: ['TEACHER'], title: '教师管理面板'}
        },{
            path: '/teacher/addStudent',
            name: 'AddStudent',
            component: () => import('@/components/AddStudent.vue'),
            meta: {requiresAuth: true, roles: ['TEACHER'], title: '添加学生用户'}
        },{
            path: '/teacher/paperAudit',
            name: 'PaperAudit',
            component: () => import('@/components/paper/PaperAudit.vue'),
            meta: {requiresAuth: true, roles: ['TEACHER'], title: '论文审核'}
        }
    ],
    STUDENT: [
        {
            path: '/student/papers',
            name: 'StudentPaperManagement',
            component: () => import('@/views/StudentPaperManagement.vue'),
            meta: { requiresAuth: true, roles: ['STUDENT'], title: '论文管理' }
        },
        {
            path: '/student/papers/detail/:id',
            name: 'PaperDetail',
            component: () => import('@/components/paper/PaperDetail.vue'),
            meta: { requiresAuth: false, title: '论文详情' },
            props: true
        },
        {
            path: '/student/papers/add',
            name: 'SubmitPaper',
            component: () => import('@/components/paper/SubmitPaper.vue'),
            meta: { requiresAuth: true, roles: ['STUDENT', 'TEACHER'], title: '论文添加' }
        },
        {
            path: '/student/papers/edit/:id',
            name: 'PaperEdit',
            component: () => import('@/components/paper/PaperEdit.vue'),
            meta: { requiresAuth: true, roles: ['STUDENT', 'TEACHER'], title: '论文修改' }
        }
    ]
};

// 合并所有路由
const routes = [
    ...baseRoutes,
    ...authRoutes,
    ...roleRoutes.ADMIN,
    ...roleRoutes.TEACHER,
    ...roleRoutes.STUDENT,
    // 修改根路径路由
    {
        path: '/',
        redirect: (to) => {
            // 添加安全判断，避免循环重定向
            if (to.redirectedFrom && to.redirectedFrom === '/') {
                return { name: 'Dashboard' }; // 安全回退
            }

            const authStore = useAuthStore();
            if (authStore.isAuthenticated) {
                const userType = authStore.user?.userType;
                if (userType === 'ADMIN') return { name: 'AdminDashboard' };
                if (userType === 'TEACHER') return { name: 'TeacherDashboard' };
                if (userType === 'STUDENT') return { name: 'StudentDashboard' };
                return { name: 'Dashboard' };
            }
            return { name: 'Login' };
        }
    },
    {
        path: '/:pathMatch(.*)*',
        name: 'NotFound',
        component: () => import('@/views/Exception/NotFound.vue'),
        meta: { requiresAuth: false, title: '页面不存在' }
    }
];

const router = createRouter({
    history: createWebHistory(import.meta.env.BASE_URL),
    routes,
    scrollBehavior() {
        return { top: 0 };
    }
});

// 在router.js中添加路由元信息验证
router.beforeEach(async (to, from) => {
    const authStore = useAuthStore()

    // 设置标题
    document.title = to.meta.title || '学术管理系统'

    // 需要认证但未登录
    if (to.meta.requiresAuth && !authStore.isAuthenticated) {
        return {
            name: 'Login',
            query: { redirect: to.fullPath },
            replace: true
        }
    }

    // 已登录但访问登录页
    if (to.name === 'Login' && authStore.isAuthenticated) {
        return { path: '/' }
    }

    // 角色权限检查
    if (to.meta.roles) {
        const userRole = authStore.user?.userType
        if (!to.meta.roles.includes(userRole)) {
            console.warn(`角色权限不足: 需要 ${to.meta.roles}, 当前 ${userRole}`)
            return { name: 'Forbidden', replace: true }
        }
    }

    return true
})
export default router;